use anyhow::Result;
use napi_derive_ohos::napi;
use sevenz_rust2::{
    encoder_options::{AesEncoderOptions, Lzma2Options},
    ArchiveWriter, EncoderConfiguration, Password,
};

#[napi]
pub struct Compress {}

#[napi]
impl Compress {
    #[napi]
    pub async fn compress_to_path(src: String, dest: String) -> Result<()> {
        sevenz_rust2::compress_to_path(src, dest)?;
        Ok(())
    }

    #[napi]
    pub async fn compress_to_path_encrypted(
        src: String,
        dest: String,
        passwd: String,
    ) -> Result<()> {
        let pwd = Password::from(passwd.as_str());
        sevenz_rust2::compress_to_path_encrypted(src, dest, pwd)?;
        Ok(())
    }

    fn compress_with_content_methods(
        src_path: String,
        create_path: String,
        methods: Vec<EncoderConfiguration>,
    ) -> Result<()> {
        if let Ok(mut sz) = ArchiveWriter::create(create_path) {
            sz.set_content_methods(methods);
            sz.push_source_path(src_path, |_| true)?;
            sz.finish()?;
        }
        Ok(())
    }

    #[napi]
    pub async fn compress_with_preset(
        src_path: String,
        create_path: String,
        passwd: String,
        level: u32,
    ) -> Result<()> {
        let pwd = Password::from(passwd.as_str());
        let methods = vec![
            AesEncoderOptions::new(pwd).into(),
            Lzma2Options::from_level(level).into(),
        ];
        Self::compress_with_content_methods(src_path, create_path, methods)?;
        Ok(())
    }
}
